package server;

import org.dom4j.Element;

import java.io.File;

/**
 * Host
 */
public class Host extends BaseContainer<Context> {
    private String name;
    private String appBase;

    /**
     * 读取 Host 配置，创建 Host 实例
     *
     * @param node
     * @return
     * @throws Exception
     */
    public static Host build(Element node) throws Exception {
        String name = node.attributeValue("name");
        String appBase = node.attributeValue("appBase");
        if (name == null || appBase == null) {
            throw new Exception("Host节点需要配置 name 和 appBase 属性");
        }
        Host host = new Host();
        host.name = name;
        host.appBase = appBase;
        host.init();
        return host;
    }

    // 初始化 Host
    private void init() throws Exception {
        // 扫描 context
        scanContext();
    }

    public String getName() {
        return name;
    }

    public Context getContext(String contextName) {
        return getChild(contextName);
    }

    /**
     * 扫描已布置的 context 目录
     *
     * @throws Exception
     */
    public void scanContext() throws Exception {
        File appBaseDir = new File(appBase);
        if (!appBaseDir.exists() || !appBaseDir.isDirectory()) {
            throw new Exception(String.format("Host路径[%s]不存在", appBaseDir));
        }
        // 获取 context 目录
        final File[] contextDirs = appBaseDir.listFiles(File::isDirectory);
        if (contextDirs != null) {
            for (File contextDir : contextDirs) {
                addContext(contextDir);
            }
        }
    }

    /**
     * 处理扫描到的 context 目录
     * @param contextDir
     * @throws Exception
     */
    public void addContext(File contextDir) throws Exception {
        Context context = Context.build(this, contextDir);
        addChildren(context.getName(), context);
    }
}
